<?php

class DefaultScope extends CActiveRecordBehavior {
	
	public $relatedFields = array();
	public $adminIgore = true;
	public $boundKeyName = ':____adminId';
	public $autoRun = true;
	
	public function related() {
		if(Yii::app()->adminUser->isGuest) return;
		list($module) = explode('/', Yii::app()->request->getPathInfo());
		if($module != 'admin' || ($this->adminIgore && Yii::app()->adminUser->role == AdminUser::ROLE_OPERATOR))
			return;
		$ownerCriteria = $this->getOwner()->getDbCriteria();
		$criteria = new CDbCriteria();
		$boundKeyName = $this->boundKeyName;
		$count = 0;
		foreach($this->relatedFields as $one) {
			if(strpos($one, '.') !== false) {
				$nodes = explode('.', $one);
				$fieldName = array_pop($nodes);
				$withPath = join('.', $nodes);
				$alias = str_replace('.', '_', $withPath);
				$condition = "`{$alias}`.`{$fieldName}` = {$boundKeyName}";
				$currentCriteria = new CDbCriteria(array(
					'with' => array($withPath=>array(
						'alias' => $alias,
						'condition'=>$condition,
					))
				));
			} else {
				$fieldName = $one;
				$alias = $ownerCriteria->alias ? $ownerCriteria->alias : 't';
				$currentCriteria = new CDbCriteria(array(
					'condition' => "`{$alias}`.`{$fieldName}` = {$boundKeyName}",
				));
			}
			
			$criteria->mergeWith($currentCriteria, false);
			
		}
		if($this->relatedFields) {
			
			$ownerCriteria->mergeWith($criteria);
			$ownerCriteria->params[$boundKeyName] = Yii::app()->adminUser->id;
		}
		return $this->owner;
	}
	
	
	public function afterConstruct($event) {
		if(!$this->autoRun) return;
		$this->related();
	}

}

?>
